<template>
    <div class="chart-container">
        <Title :title="title" class="chart-title"></Title>
        <div ref="bottom3" class="chart-content"></div>
    </div>
</template>
<script>
import { Box } from '@antv/g2plot';
import { get } from '@/utils/request';

export default {
    data() {
        return {
            title: '噪声监测',
            chart: null
        }
    },
    methods: {
        // 从接口获取今日噪声数据
        async fetchNoiseData() {
            try {
                const response = await get('http://106.14.227.138:7001/dashboard/pageQueryTodayData?page=1&pageSize=10');
                
                if (response.status === 200 && response.data?.list?.length) {
                    return this.transformNoiseData(response.data.list);
                } else {
                    console.warn('未获取到噪声数据');
                    return [];
                }
            } catch (error) {
                console.error('噪声数据请求失败:', error);
                return [];
            }
        },

        // 转换数据为箱线图格式
        transformNoiseData(rawList) {
            const deviceData = {};
            
            rawList.forEach(item => {
                const deviceId = `设备${item.device_id}`;
                const noiseValue = parseFloat(item.noise);
                
                if (!deviceData[deviceId]) {
                    deviceData[deviceId] = { values: [] };
                }
                
                deviceData[deviceId].values.push(noiseValue);
            });
            
            return Object.entries(deviceData).map(([deviceId, { values }]) => {
                const sorted = values.sort((a, b) => a - b);
                const len = sorted.length;
                
                return {
                    x: deviceId,
                    low: sorted[0],
                    q1: this.calculateQuartile(sorted, 25),
                    median: this.calculateQuartile(sorted, 50),
                    q3: this.calculateQuartile(sorted, 75),
                    high: sorted[len - 1]
                };
            });
        },

        // 计算四分位值
        calculateQuartile(sortedData, percentile) {
            const index = (percentile / 100) * (sortedData.length - 1);
            const floorIndex = Math.floor(index);
            const ceilIndex = Math.ceil(index);
            
            if (floorIndex === ceilIndex) {
                return sortedData[floorIndex];
            }
            
            return sortedData[floorIndex] + (sortedData[ceilIndex] - sortedData[floorIndex]) * (index - floorIndex);
        },

        // 初始化箱线图（调整位置和样式）
        initBoxPlot(data) {
            const container = this.$refs.bottom3;
            if (!container || !data.length) return;

            if (this.chart) {
                this.chart.destroy();
            }

            this.chart = new Box(container, {
                // 让图表填满容器
                autoFit: true,
                height: '100%',
                
                data: data,
                xField: 'x',
                yField: ['low', 'q1', 'median', 'q3', 'high'],
                
                // 去除所有文字说明
                legend: false,
                meta: {
                    y: {
                        alias: '', // 移除Y轴标题
                        min: 0
                    }
                },
                
                // 箱体样式（青色，完全不透明）
                boxStyle: {
                    stroke: '#00CED1',
                    fill: '#00FFFF',
                    fillOpacity: 1,
                    lineWidth: 2.5
                },
                
                // 须线样式
                whiskerStyle: {
                    stroke: '#00CED1',
                    lineWidth: 2
                },
                
                // 中位数线样式
                medianStyle: {
                    stroke: '#FF6347',
                    lineWidth: 3
                },
                
                // X轴样式（白色，无额外说明）
                xAxis: {
                    label: {
                        style: {
                            fill: '#FFFFFF',
                            fontWeight: 'bold',
                            fontSize: 12
                        }
                    },
                    line: {
                        style: {
                            stroke: '#FFFFFF',
                            lineWidth: 1.5
                        }
                    },
                    tickLine: {
                        style: {
                            stroke: '#FFFFFF'
                        }
                    },
                    title: false // 移除X轴标题
                },
                
                // Y轴样式（白色，无额外说明）
                yAxis: {
                    label: {
                        style: {
                            fill: '#FFFFFF',
                            fontWeight: 'bold',
                            fontSize: 12
                        }
                    },
                    line: {
                        style: {
                            stroke: '#FFFFFF',
                            lineWidth: 1.5
                        }
                    },
                    tickLine: {
                        style: {
                            stroke: '#FFFFFF'
                        }
                    },
                    title: false // 移除Y轴标题
                },
                
                // 隐藏统计项的文字标签
                label: false,
                
                animation: true
            });

            this.chart.render();
        }
    },
    async mounted() {
        const noiseData = await this.fetchNoiseData();
        this.$nextTick(() => this.initBoxPlot(noiseData));
    },
    beforeDestroy() {
        if (this.chart) {
            this.chart.destroy();
        }
    }
}
</script>
<style scoped>
/* 弹性盒容器样式，确保图表居中填满 */
.chart-container {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
}

/* 标题样式，放置在上方 */
.chart-title {
    margin-bottom: 8px;
}

/* 图表内容区域，占满剩余空间并居中 */
.chart-content {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
}

/*  tooltip样式调整 */
::v-deep .g2-tooltip {
    background: #000000;
    border: 1px solid #FFFFFF;
    border-radius: 4px;
    padding: 8px 12px;
    box-shadow: 0 2px 8px rgba(255, 255, 255, 0.2);
}

::v-deep .g2-tooltip-item {
    margin: 3px 0;
    color: #FFFFFF;
}
</style>
    